<?php

use Phalcon\Mvc\Model\Criteria;

class mainTask extends \Phalcon\CLI\Task
{

	public function mainAction() {
		$start = time();
		
		// Rss url
		$rssUrl = 'http://thethao.vnexpress.net/rss/tin-moi-nhat.rss';
		
		// Read rss content
		$document = new DOMDocument();
		$document->load($rssUrl);
		
		// Read news
		$items = $document->getElementsByTagName('item');
		
		// Insert data into db
		foreach ($items as $item) {
			// First check guid is existed?
			$guid = $item->getElementsByTagName('guid')->item(0)->nodeValue;
			$isExisted = News::findFirst("guid = '" . mysql_real_escape_string($guid) . "'");
			if (count($isExisted) == 1) {
				continue; // Jump to next if existed
			}
			
			// Insert new row if not existed
			$news = new News();
			
			$news->guid = $guid;
			
			$news->title = $item->getElementsByTagName('title')->item(0)->nodeValue;
			
			$description = explode('</br>', $item->getElementsByTagName('description')->item(0)->nodeValue);
			$news->description_link = $description[0];
			$news->description_text = $description[1];
			
			$news->public_date = date('Y-m-d H:i:s', strtotime($item->getElementsByTagName('pubDate')->item(0)->nodeValue));
			
			$news->link = $item->getElementsByTagName('link')->item(0)->nodeValue;
			
			$news->del_flg = 0;
			
			$news->created = date('Y-m-d H:i:s');
			
			// Save row
			$news->save();
		}
		
		$end = time();
		
		echo 'Completed! Used ', ($end - $start), ' seconds.';
	}

}